package com.zz.bid.service;

import com.zz.bid.exception.base.BidException;
import com.zz.bid.mapper.BidFlowMapper;
import com.zz.bid.pojo.entity.BidFlowEnum;
import com.zz.bid.pojo.to.BidFlowDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class BidFlowService {
    @Autowired
    BidFlowMapper flowMapper;

    public void addFlows(int bidId, String userName) throws BidException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (BidFlowEnum flowEnum : BidFlowEnum.values()) {
                BidFlowDetails bidFlowDetails = new BidFlowDetails();
                bidFlowDetails.setBidId(bidId);
                bidFlowDetails.setFlowId(flowEnum.getId());
                bidFlowDetails.setLastUpdateTime(sdf.format(new Date()));
                bidFlowDetails.setLastUpdateUser(userName);
                bidFlowDetails.setApproved(false);
                flowMapper.insert(bidFlowDetails);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }

    public List<BidFlowDetails> getByBidId(int bidId) throws BidException {
        try {
            return flowMapper.getBidFlows(bidId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }

    public void updateFlow(BidFlowDetails bidFlowDetails) throws BidException {
        try {
            flowMapper.update(bidFlowDetails);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }

    public void approved(Integer bidId, Integer flowId, String user) throws BidException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            BidFlowDetails bidFlowDetails = flowMapper.getBidFlow(bidId, flowId);
            bidFlowDetails.setApproved(!bidFlowDetails.isApproved());
            bidFlowDetails.setLastUpdateUser(user);
            bidFlowDetails.setLastUpdateTime(sdf.format(new Date()));
            flowMapper.update(bidFlowDetails);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BidException(e.getMessage());
        }
    }
}
